<template>
  <div class="container">
    <div class="input-section">
      <div class="input-container">
        <h2 class="title">请输入数字验证码</h2>
        <input
          type="number"
          v-model="code"
          placeholder="请输入验证码"
          class="code-input"
          maxlength="4"
          ref="codeInput"
          @input="limitInput"
        >
        <div class="button-row">
          <button @click="clearCode" class="clear-btn" :disabled="!code">清空</button>
          <button @click="toStartProcess" class="confirm-btn" :disabled="!code">确认</button>
        </div>
      </div>
    </div>

    <!-- 扫码界面 -->
    <div v-if="isScanning" class="scan-container">
      <video ref="video" class="camera-view"></video>
      <div class="scan-frame"></div>
      <!-- <button @click="stopScan" class="stop-scan-btn">取消扫描</button> -->
    </div>

    <!-- 成功提示 -->
    <div v-if="showSuccess" class="success-message">
      提交成功，请耐心等待学生认证
    </div>
  </div>
</template>

<script>
import QrScanner from 'qr-scanner'

export default {
  name: 'VerificationScanner',
  data() {
    return {
      code: '',
      isScanning: false,
      qrScanner: null,
      scanResult: '',
      showSuccess: false,
      codeList: [
            "0621", "0421", "0521", "0321", "0437", "0415", "0905", "0420", "7474",
            "8484", "9494", "1313", "1212", "1111", "1414", "1515", "1616", "1717",
            "1818", "1919", "2121", "2222", "2323", "2424", "2525", "2626", "2727",
            "2828", "2929", "3131", "3232", "3333", "3434", "3535", "5185", "9610",
            "4141", "4242", "4343", "4444", "4545", "4646", "4747", "4848", "4949",
            "5151", "5252", "5353", "5454", "5555", "5656", "5757", "5858"
          ]
    }
  },
  computed: {
    isValidCode() {
      return /^\d{4}$/.test(this.code)
    }
  },
  mounted() {
    this.$refs.codeInput.focus()
    QrScanner.WORKER_PATH = 'qr-scanner-worker.min.js'
  },
  beforeDestroy() {
    this.stopScan()
  },
  methods: {
    limitInput(event) {
      let value = event.target.value
      value = value.replace(/\D/g, '')
      this.code = value.slice(0, 4)
    },
    clearCode() {
      this.code = ''
    },
    async toStartProcess() {
      const response = await this.$axios.get(
          '/scan/setCheckConnect',
          {
          params: {
            code: this.code,
          }
        })
        if (response.data.flag) {
          this.$router.push("/sc?code="+this.code)
        }
    },
    async startProcess() {
      // if (!this.isValidCode) {
      //   alert('请输入4位数字验证码')
      //   return
      // }
      if(!this.codeList.includes(this.code)){
        this.$message({
          message: '验证码无效！'
        });
			  return
		  }
      try {
        this.isScanning = true
        await this.$nextTick()

        const videoElement = this.$refs.video
        this.qrScanner = new QrScanner(
          videoElement,
          result => {
            this.scanResult = result.data
            this.submitData()
          },
          {
            preferredCamera: 'environment',
            highlightScanRegion: true,
            maxScansPerSecond: 5
          }
        )

        await this.qrScanner.start()
      } catch (error) {
        console.error('扫码失败:', error)
        alert('扫码失败: ' + error.message)
        this.stopScan()
      }
    },
    stopScan() {
      if (this.qrScanner) {
        this.qrScanner.stop()
        this.qrScanner.destroy()
        this.qrScanner = null
      }
      this.isScanning = false
    },
    async submitData() {
      try {
        // 停止扫描
        this.stopScan()

        // 调用API提交数据
        const response = await this.$axios.get(
          '/scan/setScan',
          {
          params: {
            code: this.code,
            url: this.scanResult
          }
        }
        )
        if (response.flag) {
          this.showSuccess = true
          setTimeout(() => {
            this.showSuccess = false
            this.code = ''
            this.$refs.codeInput.focus()
          }, 3000)
        }
      } catch (error) {
        console.error('提交失败:', error)
      }
    }
  }
}
</script>

<style scoped>
.container {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}
.input-section {
  margin-top: 50px;
}
.input-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.title {
  font-size: 1.5rem;
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}
.code-input {
  border: 1px solid #ddd;
  height: 50px;
  padding: 0 15px;
  border-radius: 8px;
  font-size: 1rem;
  background-color: #f9f9f9;
  width: 100%;
  box-sizing: border-box;
}
.button-row {
  display: flex;
  gap: 10px;
}
button {
  height: 50px;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  cursor: pointer;
  flex: 1;
  transition: background-color 0.3s;
}
button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
.clear-btn {
  background-color: #f0f0f0;
  color: #333;
}
.confirm-btn {
  background-color: #007aff;
  color: white;
}
.scan-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: black;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}
.camera-view {
  width: 100%;
  max-width: 500px;
  max-height: 70vh;
}
.scan-frame {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 70%;
  height: 200px;
  border: 3px solid #4cd964;
  border-radius: 8px;
  pointer-events: none;
}
.stop-scan-btn {
  margin-top: 20px;
  padding: 10px 20px;
  background-color: #ff3b30;
  color: white;
}
.success-message {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 20px;
  border-radius: 8px;
  z-index: 1001;
  animation: fadeOut 3s forwards;
}
@keyframes fadeOut {
  0% { opacity: 1; }
  80% { opacity: 1; }
  100% { opacity: 0; visibility: hidden; }
}
</style>
